from django.shortcuts import render
from django.http import HttpResponseRedirect
# reverse 反向使用url，
#     path('<int:flight_id>', views.book, name='book') 根据name获取路径
from django.urls import reverse

from .models import Flight, Passenger


# Create your views here.
# 默认页，显示所有航班
def index(request):
    return render(request, "flights/index.html", {
        "flights": Flight.objects.all()
    })


# 航班详细信息
def flight(request, flight_id):
    # pk: primary key 主键
    flight = Flight.objects.get(pk=flight_id)
    passengers = flight.passengers.all()  # 显示所有乘客
    non_passengers = Passenger.objects.exclude(flights=flight).all()  # 显示所有未在此航班乘客
    # print(flight.id)
    # print(passengers)
    # print(non_passengers)
    return render(request, "flights/flight.html", {
        "flight": flight,
        "passengers": passengers,  # 显示所有乘客
        "non_passengers": non_passengers
    })


# 添加乘客到航班
def book(request, flight_id):
    if request.method == "POST":
        # print(request.POST)
        flight = Flight.objects.get(pk=flight_id)
        passenger = Passenger.objects.get(pk=int(request.POST["passenger"]))
        passenger.flights.add(flight)
        # reverse 反向解析路径
        return HttpResponseRedirect(reverse("flights:flight", args=(flight.id,)))  # 重定向回到航班详情页面
